import type { ActionType, EditableFormInstance, ProColumns } from '@ant-design/pro-components';
import { EditableProTable, useRefFunction } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { Button, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

interface DataSourceType {
  id: React.Key
  zdmc?: string
}

export interface ICompleteProps {
  readonly: boolean
  form: FormInstance
}

const loopDataSourceFilter = (
  data: readonly DataSourceType[],
  id: React.Key | undefined,
): DataSourceType[] => {
  return data
    .map((item) => {
      if (item.id !== id)
        return item;

      return null;
    })
    .filter(Boolean) as DataSourceType[];
};

export const Complete: React.FC<ICompleteProps> = ({ readonly = false, form }) => {
  const actionRef = useRef<ActionType>();
  const editableFormRef = useRef<EditableFormInstance>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [tableColumns, setTableColumns] = useState<ProColumns<DataSourceType>[]>([]);

  const removeRow = useRefFunction((record: DataSourceType) => {
    const data = form.getFieldValue(['programme_book', 'perfect']);
    form.setFieldValue(['programme_book', 'perfect'], loopDataSourceFilter(data, record.id));
  });

  const columns: ProColumns<DataSourceType>[] = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   width: '14%',
    // },
    {
      title: '制度名称',
      dataIndex: 'zdmc',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      valueType: 'option',
      width: 140,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            removeRow(record);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  useEffect(() => {
    setTableColumns(
      readonly ? columns.filter(item => item.dataIndex !== 'action') : columns,
    );
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [readonly]);

  return (
    <>
      <EditableProTable<DataSourceType>
        rowKey="id"
        actionRef={actionRef}
        editableFormRef={editableFormRef}
        headerTitle={
          readonly
            ? <></>
            : <Space>
            <Typography.Text>完善制度情况:</Typography.Text>
            <Button type="primary" onClick={() => {
              actionRef.current?.addEditRecord?.({
                id: (Math.random() * 1000000).toFixed(0),
              });
            }}>新增</Button>
          </Space>
        }
        // maxLength={5}
        // 关闭默认的新建按钮
        recordCreatorProps={false}
        columns={tableColumns}
        name={['programme_book', 'perfect']}
        // request={async () => ({
        //   data: defaultData,
        //   total: 3,
        //   success: true,
        // })}
        // value={dataSource}
        // onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          onChange: setEditableRowKeys,
        }}
      />
    </>
  );
};
